package cn.tedu.boot52.controller;

import cn.tedu.boot52.entity.User;
import cn.tedu.boot52.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(User user,MultipartFile picFile) throws IOException {
        User u =mapper.check(user.getUsername());
        if (u!=null){
            return 2;//代表已经存在
        }

        //原文件名
        String fileName=picFile.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;//唯一文件名
        String dirPath="E:/upload/weibo";
        File dirFile=new File(dirPath);
        if (!dirFile.exists()){//如果文件夹不存在则创建
            dirFile.mkdirs();
        }
        String filePath=dirPath+"/"+fileName;//图片完整路径
        picFile.transferTo(new File(filePath));//保存文件
        //把图片的绝对路径添加到user对象中
        user.setUrl("/"+fileName);
        //保存到数据库
        mapper.insert(user);

        return 1;
    }
    @RequestMapping("/login")
    public int login(User user, HttpSession session){
        User u=mapper.check(user.getUsername());
        if (u!=null){//查询到了
            if (user.getPassword().equals(u.getPassword())){
                //把登录查询到的用户详情对象 保存到session会话对象中
                session.setAttribute("user",u);

                return 1;//登录成功
            }else{
                return 3;//密码错误!
            }

        }
        return 2;//用户名不存在

    }
    @RequestMapping("/checkLogin")
    public User checkLogin(HttpSession session){
        //取出登录成功时保存的user对象
        User user= (User) session.getAttribute("user");
        return user;

    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除登录成功时保存的用户对象
        session.removeAttribute("user");
    }
}
